#include "timestamp.h"
#include <stdio.h>
#include <inttypes.h>
#include <sys/time.h>

Timestamp::Timestamp(int64_t micro_second_timestamp) : micro_second_timestamp_(micro_second_timestamp)
{}

std::string Timestamp::ToString() const
{
	char buf[32] = {0};
	int64_t seconds = micro_second_timestamp_ / kMicroSecondsPerSecond;
	int64_t microseconds = micro_second_timestamp_ % kMicroSecondsPerSecond;
	snprintf(buf, sizeof(buf)-1, "%" PRId64 ".%06" PRId64 "", seconds, microseconds);
	return buf;
}

std::string Timestamp::ToFormattedString() const
{
	char buf[32];
	time_t seconds = static_cast<time_t>(micro_second_timestamp_ / kMicroSecondsPerSecond);
	int microseconds = static_cast<int>(micro_second_timestamp_ % kMicroSecondsPerSecond);
	struct tm tm_time;
	gmtime_r(&seconds, &tm_time);
	snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d", tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, microseconds);
	return buf;
}

Timestamp Timestamp::GetNow()
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	int64_t seconds = tv.tv_sec;
	return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec);
}

Timestamp Timestamp::GetAfter(int64_t delay)
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	int64_t seconds = tv.tv_sec;
	return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec + delay);
}